package com.ld.admin.websocket.chat.transformer;

import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ld.admin.websocket.chat.model.ChatMessage;
import com.ld.shieldsb.common.core.util.DateUtil;

/**
 * 发送信息处理器，将信息转换为json格式发送给客户端
 * 
 * @ClassName ChatMessageSender
 * @author <a href="mailto:donggongai@126.com" target="_blank">吕凯</a>
 * @date 2019年2月27日 上午10:49:58
 *
 */
public class ChatMessageSender implements Encoder.Text<ChatMessage> {
    @Override
    public void init(final EndpointConfig config) {
    }

    @Override
    public void destroy() {
    }

    @Override
    public String encode(final ChatMessage chatMessage) throws EncodeException {
        JSONObject obj = new JSONObject();
        obj.put("message", chatMessage.getMessage());
        obj.put("sender", chatMessage.getSender());
        obj.put("senderName", chatMessage.getSenderName());
        obj.put("received", DateUtil.getDateTimeString(chatMessage.getReceived()));
        obj.put("receivedTime", DateUtil.getDateStr(chatMessage.getReceived(), "HH:mm:ss"));
        obj.put("sendAll", chatMessage.getSendAll());
        obj.put("msgType", chatMessage.getMsgType());

        return JSON.toJSONString(obj, SerializerFeature.BrowserCompatible);
    }
}
